
package com.epam.android.training.level1.activity;

import com.epam.android.training.level1.R;
import com.epam.android.training.level1.db.dao.RssDao;
import com.epam.android.training.level1.db.dao.impl.RssDaoImpl;
import com.epam.android.training.level1.rss.ItemBo;
import com.epam.android.training.level1.util.DateUtils;

import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.TextView;

import java.net.URL;
import java.util.Date;
import java.util.List;

/**
 * @author Anton Novikau
 */
public class SingleFeedActivity extends BasePageActivity {

  private ExpandableListView feedItemContainer;

  private FeedArticlesAdapter feedItemsAdapter;

  private LayoutInflater inflater;

  private RssDao rssDao;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.news_items);
    feedItemContainer = (ExpandableListView) findViewById(R.id.feed_item_container);

    inflater = getLayoutInflater();

    Intent intent = getIntent();
    long feedId = intent.getLongExtra(FEED_ID_EXTRA, -1);
    if (feedId > 0) {
      populateItems(feedId);
      addFoldUnfoldAction();
      addOpenArticleAction();
      // TODO: fix mark as read
      // addGroupCollapseAction();
    }
  }

  private void populateItems(long feedId) {
    rssDao = new RssDaoImpl(this);
    List<ItemBo> items = rssDao.findFeedItems(feedId);
    feedItemsAdapter = new FeedArticlesAdapter(items);
    feedItemContainer.setAdapter(feedItemsAdapter);
  }

  private void addFoldUnfoldAction() {
    feedItemContainer.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {

      @Override
      public void onGroupExpand(int groupPosition) {
        int groupNumber = feedItemsAdapter.getGroupCount();
        for (int i = 0; i < groupNumber; i++) {
          if (groupPosition != i && feedItemContainer.isGroupExpanded(i)) {
            feedItemContainer.collapseGroup(i);
          }
        }
      }
    });
  }

  private void addGroupCollapseAction() {
    feedItemContainer.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {

      @Override
      public void onGroupCollapse(int groupPosition) {
        ItemBo item = feedItemsAdapter.getGroup(groupPosition);
        if (!item.isRead()) {
          item.setRead(true);
          feedItemsAdapter.notifyDataSetChanged();
        }
      }
    });
  }

  private void addOpenArticleAction() {
    feedItemContainer.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

      @Override
      public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
          int childPosition, long id) {
        ItemBo feedItem = feedItemsAdapter.getChild(groupPosition, childPosition);
        URL itemLink = feedItem.getLink();
        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(itemLink.toString()));
        startActivity(browserIntent);
        return true;
      }
    });
  }

  private class FeedArticlesAdapter extends BaseExpandableListAdapter {
    private final List<ItemBo> articles;

    public FeedArticlesAdapter(List<ItemBo> articles) {
      this.articles = articles;
    }

    @Override
    public int getGroupCount() {
      return articles.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
      return 1;
    }

    @Override
    public ItemBo getGroup(int groupPosition) {
      return articles.get(groupPosition);
    }

    @Override
    public ItemBo getChild(int groupPosition, int childPosition) {
      return getGroup(groupPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
      return articles.get(groupPosition).getId();
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
      return getGroupId(groupPosition);
    }

    @Override
    public boolean hasStableIds() {
      return true;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
        ViewGroup parent) {
      TitleViewHolder holder;
      if (convertView == null) {
        holder = new TitleViewHolder();
        convertView = inflater.inflate(R.layout.feed_article_title, parent, false);
        holder.title = (TextView) convertView.findViewById(R.id.article_title);
        holder.date = (TextView) convertView.findViewById(R.id.pub_date);
        holder.time = (TextView) convertView.findViewById(R.id.pub_time);

        convertView.setTag(holder);
      } else {
        holder = (TitleViewHolder) convertView.getTag();
      }

      ItemBo item = getGroup(groupPosition);

      holder.title.setText(item.getTitle());

      Date pubDate = item.getPubDate();
      holder.date.setText(DateUtils.formatDate(pubDate));
      holder.time.setText(DateUtils.formatTime(pubDate));

      boolean isRead = item.isRead();
      if (isRead) {
        setAsReadStyle(holder.title, holder.date, holder.time);
      }
      return convertView;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
        View convertView, ViewGroup parent) {
      BodyViewHolder holder;
      if (convertView == null) {
        holder = new BodyViewHolder();
        convertView = inflater.inflate(R.layout.feed_article_body, parent, false);
        holder.body = (TextView) convertView.findViewById(R.id.article_body);
        convertView.setTag(holder);
      } else {
        holder = (BodyViewHolder) convertView.getTag();
      }

      ItemBo item = getChild(groupPosition, childPosition);
      holder.body.setText(Html.fromHtml(item.getDescription()));
      return convertView;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
      return true;
    }

    private void setAsReadStyle(TextView... textContainers) {
      for (TextView textView : textContainers) {
        textView.setTextAppearance(SingleFeedActivity.this, R.style.read_item_text);
      }
    }
  }

  private class TitleViewHolder {
    private TextView date;

    private TextView time;

    private TextView title;
  }

  private class BodyViewHolder {
    private TextView body;
  }

  private class MarkAsReadTask extends AsyncTask<Long, Void, Boolean> {

    @Override
    protected Boolean doInBackground(Long... params) {
      if (params.length > 0) {
        return rssDao.markAsRead(params[0]);
      } else {
        return Boolean.FALSE;
      }
    }
  }
}
